package com.odm.communitymanage.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.util.Log;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.LogUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @author ODM
 */
public class ImageCompressUtil {

    private ImageCompressUtil() {
    }

    private static class SingletonInstance {
        private static final ImageCompressUtil INSTANCE = new ImageCompressUtil();
    }

    public static ImageCompressUtil getInstance() {
        return SingletonInstance.INSTANCE;
    }


    /**
     * 1. 质量压缩
     * 设置bitmap options属性，降低图片的质量，像素不会减少
     * 设置options 属性0-100，来实现压缩
     *
     * @param bmp  需要压缩的bitmap图片对象
     * @param file 压缩后图片保存的位置
     */
    public  void compressImageToFile(Bitmap bmp, File file) {
        // 0-100 100为不压缩
        int options = 20;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 把压缩后的数据存放到baos中
        bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(baos.toByteArray());
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 压缩后返回bitmap
     *
     * @param bmp     需要压缩的bitmap图片对象
     * @return
     */
    public  Bitmap compressImageToBitmap(Bitmap bmp) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, os);
        if (os.toByteArray().length / 1024 > 1024) {
            //判断如果图片大于1M,进行压缩,避免在生成图片（BitmapFactory.decodeStream）时溢出
            os.reset();//重置baos即清空baos
            bmp.compress(Bitmap.CompressFormat.JPEG, 50, os);//压缩50%，把压缩后的数据存放到baos中
        }
        ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        //开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        newOpts.inPreferredConfig = Bitmap.Config.RGB_565;
        Bitmap bitmap = BitmapFactory.decodeStream(is, null, newOpts);
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        float targetHeight = 240f;// 设置高度为240f时，可以明显看到图片缩小了
        float targetWidth = 120f;// 设置宽度为120f，可以明显看到图片缩小了
        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        //scaleFactor=1表示不缩放
        int scaleFactor = 1;
        if (w > h && w > targetWidth) {//如果宽度大的话根据宽度固定大小缩放
            scaleFactor = (int) (newOpts.outWidth / targetWidth);
        } else if (w < h && h > targetHeight) {//如果高度高的话根据宽度固定大小缩放
            scaleFactor = (int) (newOpts.outHeight / targetHeight);
        }
        if (scaleFactor <= 0) {
            scaleFactor = 1;
        }
        newOpts.inSampleSize = scaleFactor;//设置缩放比例
        //重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        is = new ByteArrayInputStream(os.toByteArray());
        bitmap = BitmapFactory.decodeStream(is, null, newOpts);
        //压缩好比例大小后再进行质量压缩
//      return compress(bitmap, maxSize); // 这里再进行质量压缩的意义不大，反而耗资源，删除
        return bitmap;
    }


    /**
     * 设置图片的采样率，降低图片像素
     *
     * @param filePath
     * @param file
     */
    public  void compressBitmap(String filePath, File file) {
        // 数值越高，图片像素越低
        int inSampleSize = 8;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = false;
//      options.inJustDecodeBounds = true;//为true的时候不会真正加载图片，而是得到图片的宽高信息。
        //采样率
        options.inSampleSize = inSampleSize;
        Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 把压缩后的数据存放到baos中
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        try {
            if (file.exists()) {
                file.delete();
            } else {
                file.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(baos.toByteArray());
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public  void compressImageFile(File file) throws IOException {
        if(file == null) {
            return;
        }
        InputStream input = new FileInputStream(file);
        LogUtils.d("File Origin Size   " + FileUtils.getSize(file));
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        //开始读入图片，options.inJustDecodeBounds 设回true，只获取宽高信息
        newOpts.inJustDecodeBounds = true;
        newOpts.inPreferredConfig = Bitmap.Config.RGB_565;
        BitmapFactory.decodeStream(input, null, newOpts);
        int originWidth = newOpts.outWidth;
        int originHeight = newOpts.outHeight;
        float targetHeight = 600f;
        float targetWidth = 800f;
        //计算缩放比.由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        //scaleFactor=1表示不缩放
        int scaleFactor = 1;
        //如果宽度大的话根据宽度固定大小缩放
        if (originWidth > originHeight && originWidth > targetWidth) {
            scaleFactor = (int) (newOpts.outWidth / targetWidth);
        } else if (originWidth < originHeight && originHeight > targetHeight) {
            //如果高度高的话根据宽度固定大小缩放
            scaleFactor = (int) (newOpts.outHeight / targetHeight);
        }
        if (scaleFactor <= 0) {
            scaleFactor = 1;
        }
        //设置计算好的缩放比例
        newOpts.inSampleSize = scaleFactor;
        newOpts.inJustDecodeBounds = false;
        //注意：不可以重复使用同一个InputStream，因为会导致decodeStream返回的Bitmap为null
        InputStream is = new FileInputStream(file);
        //重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        Bitmap bitmap  = BitmapFactory.decodeStream(is, null, newOpts);
        // 把压缩后的数据存放到baos中
        if(bitmap != null){
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 40, baos);
            try {
                if (file.exists()) {
                    file.delete();
                } else {
                    file.createNewFile();
                }
                FileOutputStream fos = new FileOutputStream(file);
                fos.write(baos.toByteArray());
                fos.flush();
                fos.close();
                LogUtils.d("File Compressed  Size  " + FileUtils.getSize(file));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            Log.e("ImageCompressUtil"," bitmap == null");
        }
    }

    /**
     * 设置图片的采样率，降低图片像素
     *
     * @param filePath
     */
    public  Bitmap getCompressBitmap(String filePath) {
        // 数值越高，图片像素越低
        int inSampleSize = 8;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = false;
//      options.inJustDecodeBounds = true;//为true的时候不会真正加载图片，而是得到图片的宽高信息。
        //采样率
        options.inSampleSize = inSampleSize;
        Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 把压缩后的数据存放到baos中
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        return BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片;
    }

}